package com.heqiang.controller;

import com.heqiang.constant.Constant;
import com.heqiang.domain.Admin;
import com.heqiang.domain.result.ResultUtils;
import com.heqiang.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {

    @Autowired
    private AdminService service;

    /****************************************************** Query *****************************************************/

    /**
     * 查询-条件查询集合
     * zhang he qiang
     *
     * @Date 2020/7/23
     * @Return java.util.List<com.heqiang.domain.Admin>
     **/
    @RequestMapping("/findAll")
    public ModelAndView findAll(Admin admin, Model model) {
        log.info("==============查询管理员列表==============");
        List<Admin> adminList = service.findAll(admin);
        model.addAttribute("list", adminList);
        return new ModelAndView("/admin/list");
    }

    /**
     * 登录
     *
     * @param request
     * @param admin
     * @return com.heqiang.domain.result.Result
     * @Author zhang heqiang
     * @Date 2020/7/23
     **/
    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request, Admin admin, Model model) {
        if (null == admin || StringUtils.isEmpty(admin.getAccount()) || StringUtils.isEmpty(admin.getPassword())) {
            ResultUtils.returnError("请输入账号和密码");
        }
        Admin a = service.login(admin);
        if (null == a) {
            return new ModelAndView("/login");
        }
        WebUtils.setSessionAttribute(request, Constant.LOGIN_ADMIN, a);
        model.addAttribute("admin", a);
        return new ModelAndView("/index");
    }

    /*********************************************************** GO *******************************************************/
    //前往登陆页面
    @RequestMapping("/go/login")
    public ModelAndView goLogin() {
        return new ModelAndView("/login");
    }


    //前往错误页面(404)
    @RequestMapping("/go/error")
    public ModelAndView goError() {
        return new ModelAndView("/error");
    }

    //前往首页
    @RequestMapping("/go/index")
    public ModelAndView goIndex(HttpServletRequest request, Model model) {
        Admin admin = (Admin) WebUtils.getSessionAttribute(request, Constant.LOGIN_ADMIN);
        model.addAttribute("admin", admin);
        return new ModelAndView("/index");
    }
}
